import { BadRequestException, Inject, Injectable } from '@nestjs/common';

import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import * as svgCaptcha from 'svg-captcha';
import md5 from 'md5';
import { now } from 'lodash';
import { hash } from 'argon2';

@Injectable()
export class CodeService {
  constructor(@Inject(CACHE_MANAGER) private cache: Cache) {}
  async findAll(ip: any) {
    const key = md5('captcha' + now() + ip);
    const svg = svgCaptcha.createMathExpr({
      mathMin: 0,
      mathMax: 9,
      color: true,
      noise: 3,
    });
    //这里的svg.text就是需要的结果
    //key代表的是上面的时间戳
    await this.cache.set(key, svg.text, 1000 * 60 * 10);
    return {
      key,
      svg: svg.data,
    };
  }

  async findOne(captcha) {
    //从这里开始出错
    const cache = await this.cache.get(captcha.key);
    //判断上面取到的值和你输入的值是否相等
    if (cache != captcha.value) {
      throw new BadRequestException('验证码输入错误');
    }
  }
}
